package cn.sciento.starter.social.sina.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import cn.sciento.starter.social.core.common.api.AbstractSocialApi;
import cn.sciento.starter.social.core.common.api.SocialUser;
import cn.sciento.starter.social.core.exception.ProviderUserNotFoundException;
import cn.sciento.starter.social.core.provider.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultSinaApi extends AbstractSocialApi implements SinaApi {
  private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSinaApi.class);
  
  private String userInfoUrl;
  
  private static final ObjectMapper mapper = new ObjectMapper();
  
  public DefaultSinaApi(String accessToken, Provider provider) {
    super(accessToken);
    this.userInfoUrl = provider.getUserInfoUrl() + "?uid={openId}";
  }
  
  public SocialUser getUser(String providerUserId) {
    String result = getRestTemplate().getForObject(this.userInfoUrl, String.class, new Object[] { providerUserId });
    SinaUser user = null;
    try {
      user = (SinaUser)mapper.readValue(result, SinaUser.class);
    } catch (Exception e) {
      LOGGER.error("parse sina UserInfo error. result : {}", result);
    } 
    if (user == null || StringUtils.isBlank(user.getIdstr())) {
      LOGGER.info("not found provider user, result user={}", user);
      throw new ProviderUserNotFoundException("hoth.social.providerUserNotFound");
    } 
    return user;
  }
}
